package com.ruoyi.recruit.service.impl;

import java.util.Arrays;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.recruit.domain.RecruitContent;
import com.ruoyi.recruit.domain.RecruitUser;
import com.ruoyi.recruit.mapper.RecruitContentMapper;
import com.ruoyi.recruit.mapper.RecruitUserMapper;
import com.ruoyi.recruit.service.IRecruitUserWrittenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.recruit.mapper.RecruitUserWrittenMapper;
import com.ruoyi.recruit.domain.RecruitUserWritten;
import com.ruoyi.common.core.text.Convert;

/**
 * 笔试人员成绩Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-05-05
 */
@Service
public class RecruitUserWrittenServiceImpl extends ServiceImpl<RecruitUserWrittenMapper, RecruitUserWritten> implements IRecruitUserWrittenService
{
    @Autowired
    private RecruitContentMapper recruitContentMapper;

    @Autowired
    private RecruitUserMapper recruitUserMapper;

    /**
     * 查询笔试人员成绩
     * 
     * @param id 笔试人员成绩主键
     * @return 笔试人员成绩
     */
    @Override
    public RecruitUserWritten selectRecruitUserWrittenById(Long id)
    {
        return baseMapper.selectRecruitUserWrittenById(id);
    }

    /**
     * 查询笔试人员成绩
     *
     * @param contentId 笔试人员成绩主键
     * @return 笔试人员成绩
     */
    @Override
    public Integer selectRecruitUserWrittenByContentId(Long contentId)
    {
        return baseMapper.selectCount(new LambdaQueryWrapper<RecruitUserWritten>().eq(RecruitUserWritten::getContentId, contentId));
    }

    /**
     * 查询笔试人员成绩列表
     * 
     * @param recruitUserWritten 笔试人员成绩
     * @return 笔试人员成绩
     */
    @Override
    public List<RecruitUserWritten> selectRecruitUserWrittenList(RecruitUserWritten recruitUserWritten)
    {
        return baseMapper.selectRecruitUserWrittenList(recruitUserWritten);
    }

    /**
     * 新增笔试人员成绩
     * 
     * @param recruitUserWritten 笔试人员成绩
     * @return 结果
     */
    @Override
    public int insertRecruitUserWritten(RecruitUserWritten recruitUserWritten)
    {
        recruitUserWritten.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(recruitUserWritten);
    }

    /**
     * 修改笔试人员成绩
     * 
     * @param recruitUserWritten 笔试人员成绩
     * @return 结果
     */
    @Override
    public int updateRecruitUserWritten(RecruitUserWritten recruitUserWritten)
    {
        recruitUserWritten.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(recruitUserWritten);
    }

    /**
     * 批量删除笔试人员成绩
     * 
     * @param ids 需要删除的笔试人员成绩主键
     * @return 结果
     */
    @Override
    public int deleteRecruitUserWrittenByIds(String ids)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(ids)));
    }

    /**
     * 删除笔试人员成绩信息
     * 
     * @param id 笔试人员成绩主键
     * @return 结果
     */
    @Override
    public int deleteRecruitUserWrittenById(Long id)
    {
        return baseMapper.deleteById(id);
    }

    /**
     * 导入笔试人员信息
     *
     * @param userWrittenList 笔试人员信息
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUserWritten(List<RecruitUserWritten> userWrittenList, Long recruitId, boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userWrittenList) || userWrittenList.size() == 0)
        {
            throw new ServiceException("导入笔试人员信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (RecruitUserWritten userWritten : userWrittenList)
        {
            try
            {
                userWritten.setRecruitId(recruitId);
                // 获取招聘计划
                RecruitContent recruitContent = recruitContentMapper.selectOne(new LambdaQueryWrapper<RecruitContent>()
                        .eq(RecruitContent::getPostCode, userWritten.getPostCode().replace(" ", ""))
                        .eq(RecruitContent::getPostName, userWritten.getPostName().replace(" ", ""))
                        .eq(RecruitContent::getRecruitId, recruitId).last("limit 1"));
                if(StringUtils.isNull(recruitContent)){
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行招聘计划不存在");
                    continue;
                }
                userWritten.setContentId(recruitContent.getContentId());
                // 获取应聘人员信息
                RecruitUser recruitUser = recruitUserMapper.selectOne(new LambdaQueryWrapper<RecruitUser>()
                        .eq(RecruitUser::getIdCard, userWritten.getIdCard().replace(" ", ""))
                        .eq(RecruitUser::getContentId, recruitContent.getContentId()).last("limit 1"));
                if (StringUtils.isNull(recruitUser))
                {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行笔试人员不存在");
                    continue;
                }
                userWritten.setUserId(recruitUser.getUserId());
                //查询是否已存在到岗人员信息
                RecruitUserWritten info = baseMapper.selectOne(new LambdaQueryWrapper<RecruitUserWritten>()
                        .eq(RecruitUserWritten::getContentId, recruitContent.getContentId())
                        .eq(RecruitUserWritten::getUserId, userWritten.getUserId()).last("limit 1"));
                if(StringUtils.isNull(info)){
                    userWritten.setCreateBy(operName);
                    this.insertRecruitUserWritten(userWritten);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行笔试人员信息导入成功");
                }else if(isUpdateSupport){
                    userWritten.setId(info.getId());
                    userWritten.setUpdateBy(operName);
                    this.updateRecruitUserWritten(userWritten);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、第" + row + " 行笔试人员信息更新成功");
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、第：" + row + " 行笔试人员信息已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、第" + row + " 行笔试人员信息导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
